﻿Imports System.Runtime.CompilerServices
Imports EDMDesigner.Business
Imports EDMDesigner.Business.AssociationBase

Imports <xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">

Public Module Writer
    Public Function Write(ByVal edm As EDM, ByVal moreXElement As XElement) As XDocument
        Return New XDocument(New XDeclaration("1.0", "utf-8", Nothing), _
                    <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
                        <!-- EF Runtime content -->
                        <edmx:Runtime>
                            <!-- SSDL content -->
                            <edmx:StorageModels>
                                <%= WriterSSDL.WriteSSDL(edm.SSDLContainer) %>
                            </edmx:StorageModels>
                            <!-- CSDL content -->
                            <edmx:ConceptualModels>
                                <%= WriterCSDL.WriteCSDL(edm.CSDLContainer) %>
                            </edmx:ConceptualModels>
                            <!-- C-S mapping content -->
                            <edmx:Mappings>
                                <%= WriterMSL.WriteMSL(edm) %>
                            </edmx:Mappings>
                        </edmx:Runtime>
                        <%= WriterDesigner.WriteDesigner(edm) %>
                        <%= moreXElement %>
                    </edmx:Edmx>)
    End Function

    Friend Function GetAttribute(ByVal ns As XNamespace, ByVal attributeName As String, ByVal value As Object) As XAttribute
        If value Is Nothing Then
            Return Nothing
        End If
        If ns Is Nothing Then
            Return New XAttribute(attributeName, value)
        End If
        Return New XAttribute(ns + attributeName, value)
    End Function

    <Extension()> _
    Public Function AddAttribute(ByVal element As XElement, ByVal attribute As XAttribute) As XElement
        If attribute IsNot Nothing Then
            element.Add(attribute)
        End If
        Return element
    End Function
    <Extension()> _
    Public Function AddAttribute(ByVal element As XElement, ByVal ns As XNamespace, ByVal attributeName As String, ByVal value As Object) As XElement
        Return AddAttribute(element, GetAttribute(ns, attributeName, value))
    End Function
    <Extension()> _
    Public Function AddAttribute(ByVal element As XElement, ByVal attributeName As String, ByVal value As Object) As XElement
        Return AddAttribute(element, GetAttribute(Nothing, attributeName, value))
    End Function

    <Extension()> _
    Public Function AddElement(ByVal parentElement As XElement, ByVal childElement As XElement) As XElement
        If childElement IsNot Nothing Then
            parentElement.Add(childElement)
        End If
        Return parentElement
    End Function
End Module
